(ns main.views
  (:use 
    [clojure.string :only (blank?)]
    main.db
    ring.util.response
    [hiccup page-helpers form-helpers]
    sandbar.stateful-session))

(defn footer []
    [:div#footer
    [:p "Design by " [:a {:href "mailto:mmicunovic1@gmail.com"} "Milos Micunovic"]]])


(defn validate [& params] 
  (if (.equals (first params) "false") 
    (str "false")
    (if (= (count params) 1)
      (str "true")
      (recur (rest params)))))

(defn required [field]
  (if (blank? field)
    (do
      (str "false")
      (flash-put! :error-message "Required field left blank"))
    (str "true")))

(defn validateInstock [param]
  (try
    (Integer/parseInt param)
    (str "true")
    (catch NumberFormatException e (if (.equals param "/")
                                     (str "true")
                                     (do
                                       (flash-put! :error-message "Invalid number format")
                                       (str "false"))))))

(defn validateDouble [param]
  (try
    (Double/parseDouble param)
    (str "true")
    (catch NumberFormatException e (do 
                                     (flash-put! :error-message "Invalid price format")
                                     (str "false")))))

(defn transform-instock [param]
  (try 
    (Integer/parseInt param)
    (catch NumberFormatException e (str "/"))))

(defn layout [title & content]
  (try 
  (html5
    [:head
     [:title title]
     (include-js "/scripts/jquery-1.7.1.js")
     (include-js "/scripts/jquery.validate.js")
     (include-js "/scripts/jquery.tools.min.js")
     (include-js "/scripts/myJQuery.js")
     (include-css "/css/style.css")]
    [:body 
     [:div#logo [:a {:href "/lock"}[:img {:src "/images/logo.png"}]]]
      [:h1 title]
      [:div#clear]
      content (footer)])
  (catch Exception e 
    (do
      [:p "Unknown error, please contact system administrator"]
      (spit (str "Error-report-" (get-date) "_" (get-time) ".txt") (.printStackTrace e))))))

(defn show-error [message]
  (layout "Error"
          [:div#center-text
           [:p message]]))

(defn user-session []
  (get-user (session-get :loged-user)))

(defn article-row [x]
  [:tr
      [:td (x :label)]
      [:td (format-number (x :price))]
      [:td (x :instock)]
      [:td (x :quantity)]
      [:td (x :sub-category)]
      [:td [:a {:href (str "/article/" (x :code))} "View"]]])

(defn admin-articles [cat-name]
  (if (< (articles-count (merge {:visible 1} cat-name)) 1)
    [:p "No articles"]
    [:table
     [:tr 
      [:th "Label"]
      [:th "Price"]
      [:th "In stock"]
      [:th "Quantity"]
      [:th "Category"]
      [:th "Action"]]
     (map article-row (get-articles cat-name))]))

(defn create-admin []
  [:div {:style "border: solid green 1px; border-radius: 5px; padding: 10px;"}
  [:p "This is first time using system, register your administrator account"]
  (form-to [:post "/admin/addadministrator"]
           [:p [:label {:for "fname"} "First name"][:br] (text-field :fname) ]
           [:p [:label {:for "lname"} "Last name"][:br] (text-field :lname) ]
           [:p [:label {:for "passcode"} "Passcode"][:br] (text-field :passcode) ]
           [:p (submit-button {:id "button"} "Add Administrator")])])

(defn index-page []
    (layout "RestoSys Locked"
            (if (< (users-count {}) 1)
              (create-admin)
              (do
                [:div#center-text 
                 [:img {:src "/images/green_lock.JPG" :alt "Logout"}]
                 [:p "Enter your passcode:"]
                 (form-to {:id "loginForm"}[:get "/home"]
                          (password-field {:required "required"} :passcode)
                          (submit-button {:id "button"} "Log in"))]))))

(defn add-administrator [fname lname passcode]
  (save-user fname lname passcode "Administrator")
  (redirect "/"))

(defn article-view [code]
  (layout (str "Article " ((get-article code) :label))
          [:table#clear-table
           [:tr
            [:td#align-right "Label:"]
            [:td ((get-article code) :label)]]
           [:tr
            [:td#align-right "Price:"]
            [:td (format-number ((get-article code) :price))]]
           [:tr
            [:td#align-right "In stock:"]
            [:td ((get-article code) :instock)]]
           [:tr
            [:td#align-right "Quantity:"]
            [:td ((get-article code) :quantity)]]
           [:tr
            [:td#align-right "Sub category:"]
            [:td ((get-article code) :sub-category)]]
           [:tr
            [:td#align-right "Category:"]
            [:td ((get-article code) :category)]]]
          [:p
           (if (.equals ((user-session) :role) "Administrator")
             (do
               [:a#button {:href "/admin/articles"} "Back"
                [:a#button {:rel "#del"} "Delete"]]))
           (if (.equals ((user-session) :role) "Manager")
             [:a#button {:href "/manager"} "Back"])
           
           [:a#button {:href (str "/admin/editarticle/" ((get-article code) :code))} "Edit"]]
          
          [:div {:id "del" :class "overlay"} 
           [:p.center (str "You are about to delete " ((get-article code) :label))]
           [:p.center [:a#button {:href (str "/admin/delete" ((get-article code) :code))} "Confirm"]
           [:a#button {:class "close" :href "#"}"Abort"]]]))

(defn article-edit-view [code]
  (layout (str "Article " ((get-article code) :label))
          (form-to [:post (str "/article/" code)]
                   [:table#clear-table
                    [:tr
                     [:td#align-right "Label:"]
                     [:td (text-field {:required "required"} :label ((get-article code) :label))]]
                    [:tr
                     [:td#align-right "Price:"]
                     [:td (text-field {:required "required" :title "Invalid price format. ex: 0.99 or 0.9" :pattern "[0-9]+[.][0-9]{1,2}"} :price ((get-article code) :price))]]
                    [:tr
                     [:td#align-right "In stock:"]
                     [:td (text-field {:required "required" :title "Input number or '/' if article is unstockable" :pattern "[0-9]+|[/]"} :instock ((get-article code) :instock))]]
                    [:tr
                     [:td#align-right "Quantity:"]
                     [:td (text-field {:required "required"} :quantity ((get-article code) :quantity))]]
                    [:tr
                     [:td#align-right "Sub category:"]
                     [:td (text-field {:required "required"} :sub-category ((get-article code) :sub-category))]]
                    [:tr
                     [:td#align-right "Category:"]
                     [:td (drop-down {:required "required"} :category ["Sank" "Kuhinja"] ((get-article code) :category))]]]
                    [:p (submit-button {:id "button"} "Save")
                    [:a {:href (str "/article/" code)} "Cancel"]])))

(defn in-shift-icon [v]
  (if (== v 1)
    [:img {:src "/images/on.png"}]
    [:img {:src "/images/off.png"}]))

(defn user-view [id]
  (layout "User"
          [:table#clear-table
           [:tr
            [:td#align-right "First name:"]
            [:td ((get-user id) :fname)]]
           [:tr
            [:td#align-right "Last name:"]
            [:td ((get-user id) :lname)]]
           [:tr
            [:td#align-right "Date started:"]
            [:td ((get-user id) :date-start)]]
           [:tr
            [:td#align-right "Date finished:"]
            [:td ((get-user id) :date-end)]]
           [:tr
            [:td#align-right "Passcode:"]
            [:td ((get-user id) :passcode)]]
           [:tr
            [:td#align-right "Role:"]
            [:td ((get-user id) :role)]]
           (if (.equals ((get-user id) :role) "Waiter")
             [:tr
              [:td#align-right "Is in shift:"]
              [:td (in-shift-icon ((get-user id) :inshift))]])
           (if (.equals ((get-user id) :role) "Waiter")
             [:tr
              [:td#align-right "Todays income:"]
              [:td (str ((get-user id) :income) " EUR")]])]
          [:p
           (if (.equals ((user-session) :role) "Administrator")
             [:a#button {:href "/admin/users"} "Back"])
           (if (.equals ((user-session) :role) "Manager")
             [:a#button {:href "/manager/waiters"} "Back"])
           [:a#button {:href (str "/admin/edituser/" id)} "Edit"]
           (if-not (.equals (session-get :loged-user) id)
             [:a#button {:rel "#del"} "Delete"])
           (if (.equals ((user-session) :role) "Manager")
             [:a#button {:href (str "/manager/changeshift/" id)} "Start/End shift"]
           )]
          [:div {:id "del" :class "overlay"}
           [:p.center (str "You are about to remove " ((get-user id) :fname) " " ((get-user id) :lname))]
           [:p.center [:a#button {:href (str "/admin/removeuser/" id)} "Confirm"]
            [:a#button {:class "close"} "Abort"]]]))



(defn user-edit-view [id]
  (layout "User"
          (include-js "/scripts/jquery-ui.min.js")
          (include-css "/css/jquery.ui.datepicker.css")
          (form-to [:post (str "/user/" id)]
                   [:table#clear-table
                    [:tr
                     [:td#align-right "First name:"]
                     [:td (text-field {:required "required"} :fname ((get-user id) :fname))]]
                    [:tr
                     [:td#align-right "Last name:"]
                     [:td (text-field {:required "required"} :lname ((get-user id) :lname))]]
                    [:tr
                     [:td#align-right "Date started:"]
                     [:td (text-field {:id "datepicker" :required "required"} :date-start ((get-user id) :date-start))]]
                    [:tr
                     [:td#align-right "Date finished:"]
                     [:td (text-field {:id "datepicker2"} :date-end ((get-user id) :date-end))]]
                    [:tr
                     [:td#align-right "Passcode:"]
                     [:td (text-field {:required "required"} :passcode ((get-user id) :passcode))]]
                    [:tr
                     [:td#align-right "Role:"]
                     [:td (drop-down :role ["Waiter" "Manager" "Administrator"]((get-user id) :role))]]]
                   [:p (submit-button {:id "button"} "Save")
                    [:a {:href (str "/user/" id)} "Cancel"]])))

(defn add-article-form []
  [:div {:style "border: solid green 1px; border-radius: 5px; padding: 10px;"} 
   (include-js "/scripts/jquery-ui.min.js")
   (form-to [:post "/admin/addarticle"]
            [:p [:label {:for "label"} "Label"][:br] (text-field {:required "required"} :label) ]
            [:p [:label {:for "price"} "Price"][:br] (text-field {:required "required" :title "Invalid price format. ex: 0.99 or 0.9" :pattern "[0-9]+[.][0-9]{1,2}"} :price) ]
            [:p [:label {:for "instock"} "In stock"][:br] (text-field {:required "required" :title "Input number or '/' if article is unstockable" :pattern "[0-9]+|[/]"} :instock) ]
            [:p [:label {:for "quantity"} "Quantity"][:br] (text-field {:required "required"} :quantity) ]
            [:p [:label {:for "sub-category"} "Category"][:br] (text-field {:id "autocomplete" :required "required"} :sub-category) ]
            [:p [:label {:for "category"} "Add to"](drop-down :category ["Sank" "Kuhinja"]) ]
            [:p (submit-button {:id "button"} "Add Article")])])

(defn category-row [x]
  [:tr [:td [:a {:href (str "select" (x 0))}(x 0)]]])

(defn categories-tables [cat-name]
  [:table.left
   [:tr
    [:th cat-name]]
   (map category-row (group-by :sub-category (get-articles {:category cat-name})))])


(defn user-row [x]
  [:tr 
      [:td (x :fname)]
      [:td (x :lname)]
      [:td (x :passcode)]
      [:td (x :role)]
      [:td [:a {:href (str "/user/" (x :id))} "View"]]])

(defn users-table [t]
  (if (< (users-count t) 1)
    [:p "No users"]
  [:table
   [:tr
    [:th "First name"]
    [:th "Last name"]
    [:th "Passcode"]
    [:th "Role"]
    [:th "Action"]]
   (map user-row (get-users t))]))

(defn page-not-found []
  (layout "Page not found"
     [:div#center-text
     [:h1 "Error 404"]
     [:p "Page not found"]
     [:img {:src "/images/not-found.png"}]]))
